# Copyright (c) 2008 POTI, Inc.
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.

require 'rubygems'
require 'yaml'

$config = YAML.load_file(File.join(File.dirname(__FILE__), 'database.yaml'))

require 'drupal'
require 'wordpress'

authors = Set.new
redirects = []

def migrate_or_create_by_email(email)
  user = Wordpress::User.find_by_user_email(email)
  if user.nil?
    drupal_user = Drupal::User.find_by_mail(email)
    if drupal_user.nil?
      user = Wordpress::User.create_editor_from_email(email)
    else
      user = Wordpress::User.create_from_drupal(drupal_user)
    end
  end
  user
end

puts "Migrating Drupal blogs to Wordpress"
puts
puts "Drupal database: #{$config['drupal_database']['database']}@#{$config['drupal_database']['host']}"
puts "Wordpress database: #{$config['wordpress_database']['database']}@#{$config['wordpress_database']['host']}"
puts
puts "!!!WARNING!!! Everything (Posts, Users, Comments, Categories and Links) will be deleted in the Wordpress database."
puts
print "Do you want to continue [Y/N] ? "
c = STDIN.read(1).upcase

if c == 'Y'  
  puts "Destroying all data (this may take a while)"
  # Clear up Wordpress
  # This is slower than a delete_all but insures that relationship table are getting
  # cleared up too
  Wordpress::User.destroy_all
  Wordpress::Term.destroy_all
  
  # Clean up other stuff we don't care about
  Wordpress::Link.delete_all
  
  # Create admins in Wordpress
  $config['wordpress_database']['users']['admins'].each {|email|
    puts "Creating admin: #{email}"
    Wordpress::User.create_admin_from_email(email)
  }

  # Create default category
  Wordpress::Term.create_category('Uncategorized')
  
  # Get all the blog posts from Drupal
  nodes = Drupal::Node.find(:all, :conditions => "type='blog'")
  
  # Insert them in Wordpress
  nodes.each {|node|
    puts "Migrating: #{node.title}"
    p = Wordpress::Post.create_from_drupal(node)
    redirects << "/node/#{node.id} #{p.guid}"
    redirects << "/node/#{node.id}#comment #{p.guid}#comments"
    redirects << "/trackback/#{node.id} #{p.guid}/trackback/"
    aliases = Drupal::UrlAlias.find_aliases_for_node(node)
    aliases.each do |link|
      redirects << "/#{link.dst} #{p.guid}"
    end
    authors.add(node.user.name.downcase)
  }
  
  # Collect author feed redirects
  authors.each do |a|
    redirects << "/#{a}/blog/feed http://#{Wordpress::FEED_HOST}/author/#{a}/feed" 
    redirects << "/#{a}/blog http://#{Wordpress::FEED_HOST}/author/#{a}" 
  end
  
  # Collect category redirects
  Wordpress::Term.find(:all).each do |wp_term|
    redirects << "/taxonomy/term/#{Drupal::Term.find_by_name(wp_term.name).id} http://#{Wordpress::BLOG_HOST}/category/#{wp_term.slug}/"
    redirects << "/taxonomy/term/#{Drupal::Term.find_by_name(wp_term.name).id}/0/feed http://#{Wordpress::FEED_HOST}/songbird-blog/"
  end
  
  # Set up Editors
  $config['wordpress_database']['users']['editors'].each do |email|
    user = migrate_or_create_by_email(email)
    user.promote_to_editor
  end

  # Set up Authors
  $config['wordpress_database']['users']['authors'].each do |email|
    user = migrate_or_create_by_email(email)
    user.promote_to_author
  end

  # Demote those users to subscriber role
  $config['wordpress_database']['users']['subscribers'].each {|email|
    user = Wordpress::User.find_by_user_email(email)
    user.promote_to_subscriber unless user.nil?
  }
  
  # Dump redirect configuration
  5.times { puts }
  puts "#" * 80
  puts " Place these redirects in the alias_module block"
  puts " of the Apache config on the Drupal box."
  puts "#" * 80
  puts
  
  redirects.each do |rule|
    puts "Redirect 301 #{rule}"
  end
  
  puts "RedirectMatch 301 ^.*/blog/.*feed http://#{Wordpress::FEED_HOST}/songbird-blog/"
  puts "RedirectMatch 301 ^.*/blog http://#{Wordpress::BLOG_HOST}/"
  puts
  puts "#" * 80
  puts " End of redirect block. (Scroll to top.)"
  puts "#" * 80
  puts
  
end
